﻿using CCWin.Win32.Const;
using Google.Protobuf.WellKnownTypes;
using HirelReg;
using HirelSeriesH.Entity;
using HirelSeriesH.Global;
using HirelSeriesH.Tools;
using HML;
using Microsoft.Win32;
using MySql.Data.MySqlClient;
using Org.BouncyCastle.Pqc.Crypto.Falcon;
using Sunny.UI;
using Sunny.UI.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.Remoting.Channels;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Timers;
using System.Windows.Forms;

namespace HirelSeriesH
{
    public partial class ChannelManagementForm : UIForm
    {
        [DllImport("user32.dll", EntryPoint = "IsWindow")]
        public static extern bool IsWindow(IntPtr hWnd);
        [DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]
        public static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        private static extern int SendMessage(IntPtr hWnd, int msg, uint wParam, uint lParam);

        [DllImport("User32.dll", EntryPoint = "SetForegroundWindow")]
        public static extern int SetForegroundWindow(IntPtr hWnd);

        [DllImport("User32.dll", EntryPoint = "SendMessage")]
        public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, ref COPYDATASTRUCT lParam);
        [StructLayout(LayoutKind.Sequential)]
        public struct COPYDATASTRUCT
        {
            public IntPtr dwData;
            public int cbData;
            [MarshalAs(UnmanagedType.LPStr)]
            public string lpData;
        }
        private readonly string basePath = AppDomain.CurrentDomain.BaseDirectory;
        private readonly string historyFilePath = "HistoryFile.txt";

        //当前显示的老化板
        private int currChannelNum = -1;

        List<UICheckBox> CheckBoxes = new List<UICheckBox>();

        List<UILight> Lights = new List<UILight>();

        List<Label> pows = new List<Label>();

        List<CheckBox> CBS = new List<CheckBox>();

        object Sender;
        EventArgs EventArgs;

        public System.Timers.Timer TimerForRushButtons = new System.Timers.Timer();

        public System.Timers.Timer TimerForParam = new System.Timers.Timer();

        public System.Timers.Timer TimerForDATA = new System.Timers.Timer();

        public ChannelManagementForm(object sender, EventArgs e)
        {
            Sender = sender;
            EventArgs = e;

            InitializeComponent();

            CheckForIllegalCrossThreadCalls = false;

            BtnChannel01.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel01);
            BtnChannel02.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel02);
            BtnChannel03.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel03);
            BtnChannel04.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel04);
            BtnChannel05.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel05);
            BtnChannel06.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel06);
            BtnChannel07.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel07);
            BtnChannel08.Click += new EventHandler(this.BtnChannel_Click);
            Global.Global.Buttons.Add(BtnChannel08);

            CheckBoxes.Add(checkBoxChannel1);
            CheckBoxes.Add(checkBoxChannel2);
            CheckBoxes.Add(checkBoxChannel3);
            CheckBoxes.Add(checkBoxChannel4);
            CheckBoxes.Add(checkBoxChannel5);
            CheckBoxes.Add(checkBoxChannel6);
            CheckBoxes.Add(checkBoxChannel7);
            CheckBoxes.Add(checkBoxChannel8);

            Lights.Add(uiLight1);
            Lights.Add(uiLight2);
            Lights.Add(uiLight3);
            Lights.Add(uiLight4);
            Lights.Add(uiLight5);
            Lights.Add(uiLight6);
            Lights.Add(uiLight7);
            Lights.Add(uiLight8);

            pows.Add(POW1);
            pows.Add(POW2);
            pows.Add(POW3);
            pows.Add(POW4);

            this.checkBox1.CheckedChanged += new EventHandler(this.checkBox_CheckedChanged);
            this.checkBox2.CheckedChanged += new EventHandler(this.checkBox_CheckedChanged);
            this.checkBox3.CheckedChanged += new EventHandler(this.checkBox_CheckedChanged);
            this.checkBox4.CheckedChanged += new EventHandler(this.checkBox_CheckedChanged);

            CBS.Add(checkBox1);
            CBS.Add(checkBox2);
            CBS.Add(checkBox3);
            CBS.Add(checkBox4);

            //this.IR.Click += new System.EventHandler(this.TitleLable_Click);
            //this.VR.Click += new System.EventHandler(this.TitleLable_Click);

            //初始化表格内部的label实例
            for (int row = 0; row < 2; row++)
            {
                for (int column = 0; column < 4; column++)
                {
                    TextBox textBox = new TextBox();
                    textBox.ReadOnly = true;
                    textBox.BorderStyle = BorderStyle.None;
                    textBox.BackColor = Color.FromArgb(59, 59, 59);
                    textBox.Font = new Font("宋体", 10.5f, FontStyle.Regular);
                    textBox.ForeColor = Color.White;
                    textBox.Text = "";
                    textBox.TextAlign = HorizontalAlignment.Center;
                    textBox.AutoSize = false;
                    textBox.Size = new Size(48, 23);
                    textBox.Dock = DockStyle.Bottom;

                    if (row < 2)
                    {
                        if (row == 0)
                        {
                            Global.Global.LabelArrayVR.Add(textBox);
                        }
                        else if (row == 1)
                        {
                            Global.Global.LabelArrayIR.Add(textBox);
                        }
                        tableLayoutPanel1.Controls.Add(textBox, column + 1, row + 1);
                    }

                }
            }

        }

        private void ChannelManagementForm_Load(object sender, EventArgs e)
        {
            Global.Global.ChannelManagementForm = this;
            //未选择老化板
            currChannelNum = -1;

            Global.Global.CurrentChannel = null;
            if (Global.Global.UserRole == "Engineer")
            {
                this.btnTest.Visible = true;
            }
            else
            {
                this.btnTest.Visible = false;
            }
            if (Sender != null && EventArgs != null)
            {
                BtnChannel_Click(Sender, EventArgs);
            }
            else
            {
                foreach (var channel in Global.Global.ChannelList)
                {
                    channel.IsCurrentChannel = false;
                    if (channel.IsRed)
                    {
                        Global.Global.Buttons[channel.Index].FillColor = Color.Red;
                        Global.Global.Buttons[channel.Index].FillColor2 = Color.Red;
                    }
                    else if (channel.State == "running")
                    {
                        Global.Global.Buttons[channel.Index].FillColor = Color.FromArgb(107, 149, 96);
                        Global.Global.Buttons[channel.Index].FillColor2 = Color.FromArgb(107, 149, 96);
                    }
                }
            }

            TimerForRushButtons.Interval = 1000;
            TimerForRushButtons.AutoReset = true;
            TimerForRushButtons.Enabled = false;
            TimerForRushButtons.Elapsed += new ElapsedEventHandler(TimerForRushButtons_Tick);
            TimerForRushButtons.Start();

            TimerForParam.Interval = 1000;
            TimerForParam.AutoReset = true;
            TimerForParam.Enabled = false;
            TimerForParam.Elapsed += new ElapsedEventHandler(TimerForParam_Tick);
            TimerForParam.Start();

            TimerForDATA.Interval = 1000;
            TimerForDATA.AutoReset = true;
            TimerForDATA.Enabled = false;
            TimerForDATA.Elapsed += new ElapsedEventHandler(TimerForDATA_Tick);
            TimerForDATA.Start();

            this.Activate();
            LoadingForm.LoadingHelper.CloseForm();
        }

        private void TimerForRushButtons_Tick(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < Lights.Count; i++)
                {
                    if (Global.Global.FlagButtons[i])
                    {
                        Lights[i].State = UILightState.On;
                    }
                    else
                    {
                        Lights[i].State = UILightState.Off;
                    }
                }

                foreach (var btn in Global.Global.Buttons)
                {
                    if (btn.FillColor.Name == "Red")
                    {
                        continue;
                    }
                    if (int.Parse(btn.Tag.ToString()) == currChannelNum) //选中状态
                    {
                        if (Global.Global.ChannelList[int.Parse(btn.Tag.ToString())].State == "running")
                        {
                            btn.FillColor = Color.FromArgb(0, 123, 95);
                            btn.FillColor2 = Color.FromArgb(0, 123, 95);
                        }
                        else
                        {
                            btn.FillColor = SystemColors.ActiveCaption;
                            btn.FillColor2 = SystemColors.ActiveCaption;
                        }
                    }
                    else //未选中状态 
                    {
                        if (Global.Global.ChannelList[int.Parse(btn.Tag.ToString())].State == "running")
                        {
                            btn.FillColor = Color.FromArgb(107, 149, 96);
                            btn.FillColor2 = Color.FromArgb(107, 149, 96);
                        }
                        else
                        {
                            btn.FillColor = Color.FromArgb(59, 59, 59);
                            btn.FillColor2 = Color.FromArgb(59, 59, 59);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string str;
                string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                Program.WriteLog(str);
            }
        }

        private void TimerForParam_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Global.Global.CurrentChannel != null)
                {
                    Channel channel = Global.Global.CurrentChannel;
                    if (channel.TestParameter != null)
                    {
                        for (int j = 0; j < channel.PowerList.Count; j++)
                        {
                            pows[j].ForeColor = Color.White;
                            pows[j].Text = "DPS" + (j + 1).ToString() + "：";

                            //string str = channel.PowerList[j].Voltage + "V(设定值)  ";

                            string str = "";

                            if (channel.PowerList[j].IsOpen)
                            {
                                /*str = str + channel.PowerList[j].State.ToUpper() + "  ";

                                if (channel.PowerList[j].State == "on")
                                {
                                    str = str + "加电中  ";
                                }
                                else if (channel.PowerList[j].State == "off")
                                {
                                    str = str + "间歇中  ";
                                }
                                else if (channel.PowerList[j].State == "up")
                                {
                                    str = str + "升压中  ";
                                }
                                else if (channel.PowerList[j].State == "down")
                                {
                                    str = str + "降压中  ";
                                }*/

                                str = str + channel.PowerList[j].RealVoltage.ToString("0.00") + "V  " + channel.PowerList[j].RealCurrent.ToString("0.00") + "A";
                            }
                            pows[j].Text = pows[j].Text + str;
                        }
                    }
                    else
                    {

                        pows[0].ForeColor = Color.FromArgb(59, 59, 59);
                        pows[1].ForeColor = Color.FromArgb(59, 59, 59);
                        pows[2].ForeColor = Color.FromArgb(59, 59, 59);
                        pows[3].ForeColor = Color.FromArgb(59, 59, 59);
                    }
                }
            }
            catch (Exception ex)
            {
                string str;
                string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                Program.WriteLog(str);
            }
        }

        private void TimerForDATA_Tick(object sender, EventArgs e)
        {
            try
            {
                if (Global.Global.CurrentChannel != null)
                {
                    string str;
                    if (Global.Global.CurrentChannel.State == "stop")
                    {
                        str = "通道空闲中";
                    }
                    else if (Global.Global.CurrentChannel.State == "pause")
                    {

                        if (Global.Global.CurrentChannel.StateEnd)
                        {
                            str = "测试已完成";
                        }
                        else
                        {
                            str = "测试暂停中";
                        }
                    }
                    else
                    {
                        str = "测试进行中";
                    }
                    DataAreaPanel.Text = "测试数据：" + Global.Global.CurrentChannel.ChannelName + "(" + str + ")";

                    for (int i = 0; i < Global.Global.CurrentChannel.Positions.Count; i++)
                    {
                        if (Global.Global.CurrentChannel.State == "stop")
                        {
                            Global.Global.LabelArrayVR[i].Text = "";
                            Global.Global.LabelArrayIR[i].Text = "";
                        }
                        else
                        {
                            Global.Global.LabelArrayVR[i].Text = Global.Global.CurrentChannel.Positions[i].UValue.ToString();

                            string dw;
                            decimal dnum;
                            //毫安级别.
                            if (Global.Global.CurrentChannel.Positions[i].IValue * 1000 < 1000)
                            {
                                dnum = Math.Round(Global.Global.CurrentChannel.Positions[i].IValue * 1000, 1);
                                dw = "mA";
                            }
                            else //安培级别
                            {
                                dnum = Math.Round(Global.Global.CurrentChannel.Positions[i].IValue, 3);
                                dw = "A";
                            }

                            Global.Global.LabelArrayIR[i].Text = dnum.ToString() + dw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                string str;
                string strDateInfo = DateTime.Now.ToString() + " 出现应用程序未处理的异常：" + "\r\n";

                if (ex != null)
                {
                    str = string.Format(strDateInfo + "异常类型：{0}\r\n异常消息：{1}\r\n异常信息：{2}\r\n",
                         ex.GetType().Name, ex.Message, ex.StackTrace);
                }
                else
                {
                    str = string.Format("应用程序线程错误:{0}", ex);
                }
                Program.WriteLog(str);
            }
        }

        private void ChannelManagementForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            TimerForRushButtons.Stop();
            Global.Global.PowerVoltage = null;
            Global.Global.PowerCurr = null;
            Global.Global.CurrentChannel = null;
            foreach (var channel in Global.Global.ChannelList)
            {
                channel.IsCurrentChannel = false;
            }
            Global.Global.ChannelManagementForm = null;
            Global.Global.Buttons.Clear();
            Global.Global.LabelArrayIR.Clear();
            Global.Global.LabelArrayVR.Clear();
        }
        private void tableLayoutPanel1_CellPaint(object sender, TableLayoutCellPaintEventArgs e)
        {
            SolidBrush brushColumn = new SolidBrush(Color.FromArgb(59, 59, 59));
            SolidBrush brushRow = new SolidBrush(Color.FromArgb(59, 59, 59));
            if (e.Column == 0)
            {
                e.Graphics.FillRectangle(brushColumn, e.CellBounds);
            }
            if (e.Row == 0)
            {
                e.Graphics.FillRectangle(brushRow, e.CellBounds);
            }
        }

        //通道按钮选择事件动作
        public void BtnChannel_Click(object sender, EventArgs e)
        {
            Control button = (Control)sender;
            int channelNum = int.Parse(button.Tag.ToString());

            Global.Global.CurrentChannelAddress = channelNum;
            currChannelNum = channelNum;
            foreach (var btn in Global.Global.Buttons)
            {
                if (btn.FillColor.Name == "Red")
                {
                    continue;
                }
                if (int.Parse(btn.Tag.ToString()) == currChannelNum) //选中状态
                {
                    if (Global.Global.ChannelList[int.Parse(btn.Tag.ToString())].State == "running")
                    {
                        btn.FillColor = Color.FromArgb(0, 123, 95);
                        btn.FillColor2 = Color.FromArgb(0, 123, 95);
                        //btn.UseVisualStyleBackColor = false;
                    }
                    else
                    {
                        btn.FillColor = SystemColors.ActiveCaption;
                        btn.FillColor2 = SystemColors.ActiveCaption;
                        //btn.UseVisualStyleBackColor = false;
                    }
                }
                else //未选中状态 
                {
                    if (Global.Global.ChannelList[int.Parse(btn.Tag.ToString())].State == "running")
                    {
                        btn.FillColor = Color.FromArgb(107, 149, 96);
                        btn.FillColor2 = Color.FromArgb(107, 149, 96);
                        //btn.UseVisualStyleBackColor = false;
                    }
                    else
                    {
                        btn.FillColor = Color.FromArgb(59, 59, 59);
                        btn.FillColor2 = Color.FromArgb(59, 59, 59);
                        //btn.UseVisualStyleBackColor = false;
                    }
                }
            }
            foreach (var channel in Global.Global.ChannelList)
            {
                channel.IsCurrentChannel = false;
            }
            Global.Global.ChannelList[channelNum].IsCurrentChannel = true;
            Global.Global.CurrentChannel = Global.Global.ChannelList[channelNum];
            TestParamArea.Text = Global.Global.CurrentChannel.ChannelName + "测试参数";

            this.TbProductModel.Text = "";
            this.TbBatchNumber.Text = "";
            CYJG.Text = "采样间隔：";
            CXMC.Text = "程序名称：";

            powerType.Text = "电源模式：";

            if (Global.Global.CurrentChannel.TestParameter != null)
            {
                this.TbProductModel.Text = Global.Global.CurrentChannel.TestParameter.ProductModel;
                this.TbBatchNumber.Text = Global.Global.CurrentChannel.TestParameter.BatchNumber;
                CYJG.Text = "采样间隔：" + Global.Global.CurrentChannel.TestParameter.CheckInterval + "秒";
                CXMC.Text = "程序名称：" + Global.Global.CurrentChannel.TestParameter.ParaName;

                powerType.Text = "电源模式：" + (Global.Global.CurrentChannel.TestParameter.isStatic ? "静态模式" : "循环模式");
            }

            if (Global.Global.CurrentChannel.State == "stop")
            {
                //清空界面数据
                foreach (var label in Global.Global.LabelArrayIR)
                {
                    label.Text = "";
                    label.BackColor = Color.FromArgb(59, 59, 59);
                }
                foreach (var label in Global.Global.LabelArrayVR)
                {
                    label.Text = "";
                    label.BackColor = Color.FromArgb(59, 59, 59);
                }
            }

            foreach (var position in Global.Global.CurrentChannel.Positions)
            {
                CBS[position.Index].Checked = position.IsUse;
            }
        }

        private void btnClearParam_Click(object sender, EventArgs e)
        {
            List<Channel> channelList = Global.Global.ChannelList;
            List<Channel> channelListTemp = new List<Channel>();
            foreach (var checkBoxes in CheckBoxes)
            {
                if (checkBoxes.Checked)
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    channelListTemp.Add(channelList[tag]);
                }

            }
            if ((channelListTemp.Count == 0))// && (Global.Global.CurrentChannel == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要清除程序的老化板", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            //多选操作
            if (channelListTemp.Count > 0)
            {
                foreach (var channel in channelListTemp)
                {
                    if (channel.State != "stop")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "正处于非空闲状态，请先重置测试。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                }
                foreach (var channel in channelListTemp)
                {
                    channel.TestParameter = null;
                }


                //刷新
                PowerPack.refreshGlobalPowerPackList();

                UIMessageDialog.ShowMessageDialog(this, "所选老化板，测试程序已清空。", UILocalize.InfoTitle, false, UIStyle.Colorful);
            }
        }

        private void btnLoadParam_Click(object sender, EventArgs e)
        {
            List<Channel> channelList = Global.Global.ChannelList;
            List<Channel> channelListTemp = new List<Channel>();
            foreach (var checkBoxes in CheckBoxes)
            {
                if (checkBoxes.Checked)
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    channelListTemp.Add(channelList[tag]);
                }

            }
            if ((channelListTemp.Count == 0))// && (Global.Global.CurrentChannel == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要载入程序的老化板", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            //多选操作
            if (channelListTemp.Count > 0)
            {

                string IDs = "";
                foreach (var channel in channelListTemp)
                {
                    if (channel.State != "stop")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "正处于非空闲状态，请先重置测试，再载入程序。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                    IDs = IDs + channel.ID + ",";
                }
                ConfigurationForm configurationForm = new ConfigurationForm(true, "Worker", IDs);
                configurationForm.refresh += RefreshTestParam; // 父窗口加入委托 
                configurationForm.ShowDialog(this);
                return;
            }
        }

        private void RefreshTestParam()
        {
            this.TbProductModel.Text = Global.Global.CurrentChannel.TestParameter.ProductModel;
            this.TbBatchNumber.Text = Global.Global.CurrentChannel.TestParameter.BatchNumber;
            CYJG.Text = "采样间隔：" + Global.Global.CurrentChannel.TestParameter.CheckInterval + "秒";
            CXMC.Text = "程序名称：" + Global.Global.CurrentChannel.TestParameter.ParaName;

            powerType.Text = "电源模式：" + (Global.Global.CurrentChannel.TestParameter.isStatic ? "静态模式" : "循环模式");

            //刷新
            PowerPack.refreshGlobalPowerPackList();
        }

        private void BtnStartTest_Click(object sender, EventArgs e)
        {
            RegistryKey regRead;
            try
            {
                regRead = Registry.CurrentUser.OpenSubKey(@"Software\Hirel", true);
                if (regRead == null) //如果该子键不存在
                {
                    RegTipForm regTipForm = new RegTipForm("软件尚未注册，请注册。");
                    regTipForm.ShowDialog(this);
                    return;
                }
                else
                {
                    object obj = regRead.GetValue(@"RegCode");
                    string regCode = obj.ToString();
                    string expdate = RegCode.GetExpireDate(regCode);

                    if (expdate == "")
                    {
                        RegTipForm regTipForm = new RegTipForm("注册码无效，或注册码已过期，请重新注册。");
                        regTipForm.ShowDialog(this);
                        return;
                    }
                    else
                    {
                        DateTime dt1 = DateTime.Parse(expdate + " 23:59:59");
                        DateTime dt2 = DateTime.Now;
                        TimeSpan ts = dt1.Subtract(dt2);
                        double days = ts.TotalDays;

                        if (days < 10 && days > 0)
                        {
                            int odays = (int)Math.Floor(days);

                            RegTipForm regTipForm = new RegTipForm("注册码还有" + odays + "天过期，请及时重新注册。");
                            regTipForm.ShowDialog(this);
                        }
                        else if (days <= 0)
                        {
                            RegTipForm regTipForm = new RegTipForm("注册码已过期，请重新注册。");
                            regTipForm.ShowDialog(this);
                            return;
                        }

                    }
                }
                regRead.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            if (Global.Global.PtcBox.ErrorCode != "NULL")
            {
                UIMessageDialog.ShowMessageDialog(this, "温箱状态异常，不能开启测试！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            if (Global.Global.SDTest != null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先关闭手动测试窗口，再开始测试！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            List<Channel> channelList = Global.Global.ChannelList;
            List<Channel> channelListTemp = new List<Channel>();
            foreach (var checkBoxes in CheckBoxes)
            {
                if (checkBoxes.Checked)
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    channelListTemp.Add(channelList[tag]);
                }

            }
            if ((channelListTemp.Count == 0))// && (Global.Global.CurrentChannel == null)
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要开始测试的老化板", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            //多选操作
            if (channelListTemp.Count > 0)
            {
                foreach (var channel in channelListTemp)
                {
                    if (channel.State == "running")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "测试已开始,不需要重复动作", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                    if (channel.TestParameter == null)
                    {
                        UIMessageDialog.ShowMessageDialog(this, "请为" + channel.ChannelName + "载入测试参数", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                    if ((channel.State == "pause") && channel.StateEnd)
                    {
                        MessageBox.Show("当前老化板程序已执行完毕，如想重新执行请点击状态复位按钮。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        return;
                    }
                }

                if (!UIMessageDialog.ShowMessageDialog(this, "是否确定开始测试？", UILocalize.AskTitle, true, UIStyle.Colorful))
                {
                    return;
                }

                LoadingForm.LoadingHelper.ShowLoadingScreen();

                //将所有工位的电源接触器闭合或开合
                //foreach (var chn in channelListTemp)
                //{
                //    foreach (var pos in chn.Positions)
                //    {
                //        int Index = chn.Index * chn.Positions.Count + pos.Index;
                //        Global.Global.PLC_XINJE.SetDO((byte)Index, pos.IsUse);
                //        Thread.Sleep(50);
                //    }
                //}

                int nowCycleNumber = 0;

                //开启温箱
                if (Global.Global.PtcBox.IsOpen)
                {
                    for (int n = 0; n < channelListTemp.Count; n++)
                    {
                        TestParameter testParameter = channelListTemp[n].TestParameter;
                        testParameter.HighTemp = Global.Global.PtcBox.HighTemp;
                        testParameter.LowTemp = Global.Global.PtcBox.LowTemp;
                        testParameter.HighTime = Global.Global.PtcBox.HighTime;
                        testParameter.LowTime = Global.Global.PtcBox.LowTime;
                        testParameter.XieLv = Global.Global.PtcBox.XieLv;
                        testParameter.TestCycs = Global.Global.PtcBox.TestCycs;
                        testParameter.BeforTemp = Global.Global.PtcBox.BeforTemp;
                        testParameter.BeforTime = Global.Global.PtcBox.BeforTime;
                        testParameter.AfterTemp = Global.Global.PtcBox.AfterTemp;
                        testParameter.AfterTime = Global.Global.PtcBox.AfterTime;
                        testParameter.IsLineContrl = Global.Global.PtcBox.IsLineContrl;
                        testParameter.StratPos = Global.Global.PtcBox.StratPos;
                        testParameter.TempContrl = Global.Global.PtcBox.TempContrl;
                        testParameter.Ysfz = Global.Global.PtcBox.Ysfz;
                    }

                    nowCycleNumber = string.IsNullOrWhiteSpace(Global.Global.Syzq) ? (int)Global.Global.PtcBox.TestCycs : int.Parse(Global.Global.Syzq);
                }
                else
                {
                    Global.Global.PtcBox.HighTemp = channelListTemp[0].TestParameter.HighTemp;
                    Global.Global.PtcBox.LowTemp = channelListTemp[0].TestParameter.LowTemp;
                    Global.Global.PtcBox.HighTime = channelListTemp[0].TestParameter.HighTime;
                    Global.Global.PtcBox.LowTime = channelListTemp[0].TestParameter.LowTime;
                    Global.Global.PtcBox.XieLv = channelListTemp[0].TestParameter.XieLv;
                    Global.Global.PtcBox.TestCycs = channelListTemp[0].TestParameter.TestCycs;
                    Global.Global.PtcBox.BeforTemp = channelListTemp[0].TestParameter.BeforTemp;
                    Global.Global.PtcBox.BeforTime = channelListTemp[0].TestParameter.BeforTime;
                    Global.Global.PtcBox.AfterTemp = channelListTemp[0].TestParameter.AfterTemp;
                    Global.Global.PtcBox.AfterTime = channelListTemp[0].TestParameter.AfterTime;
                    Global.Global.PtcBox.IsLineContrl = channelListTemp[0].TestParameter.IsLineContrl;
                    Global.Global.PtcBox.StratPos = channelListTemp[0].TestParameter.StratPos;
                    Global.Global.PtcBox.TempContrl = channelListTemp[0].TestParameter.TempContrl;
                    Global.Global.PtcBox.Ysfz = channelListTemp[0].TestParameter.Ysfz;

                    //更新数据库状态
                    MySqlParameter[] paras = new MySqlParameter[] {
                                         new MySqlParameter("@HighTemp", channelListTemp[0].TestParameter.HighTemp.ToString()),
                                         new MySqlParameter("@LowTemp", channelListTemp[0].TestParameter.LowTemp.ToString()),
                                         new MySqlParameter("@HighTime", channelListTemp[0].TestParameter.HighTime.ToString()),
                                         new MySqlParameter("@LowTime", channelListTemp[0].TestParameter.LowTime.ToString()),
                                         new MySqlParameter("@IsLineContrl", channelListTemp[0].TestParameter.IsLineContrl),
                                         new MySqlParameter("@XieLv", channelListTemp[0].TestParameter.XieLv.ToString()),
                                         new MySqlParameter("@TestCycs", channelListTemp[0].TestParameter.TestCycs.ToString()),
                                         new MySqlParameter("@StratPos", channelListTemp[0].TestParameter.StratPos),
                                         new MySqlParameter("@TempContrl", channelListTemp[0].TestParameter.TempContrl),
                                         new MySqlParameter("@BeforTemp", channelListTemp[0].TestParameter.BeforTemp.ToString()),
                                         new MySqlParameter("@BeforTime", channelListTemp[0].TestParameter.BeforTime.ToString()),
                                         new MySqlParameter("@AfterTemp", channelListTemp[0].TestParameter.AfterTemp.ToString()),
                                         new MySqlParameter("@AfterTime", channelListTemp[0].TestParameter.AfterTime.ToString()),
                                         new MySqlParameter("@Ysfz", channelListTemp[0].TestParameter.Ysfz),
                                         new MySqlParameter("@ID", Global.Global.PtcBox.ID) };
                    DBHelper.ExecuteNonQuery(DBSql.UPDATE_PTC_BOX, 1, paras);

                    AutoRun.TimerCheckTemperature.Stop();
                    Thread.Sleep(1000);

                    //设置高低温周期运行模式
                    string strCommand = "C3=C" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定程序号为：1(随便设)
                    strCommand = "C4=1" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：1-高温浸润设定
                    strCommand = "C5=1" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置高温温度
                    strCommand = "C6=" + Global.Global.PtcBox.HighTemp + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置高温持续时间
                    TimeSpan spWorkMin = TimeSpan.FromMinutes((double)Global.Global.PtcBox.HighTime);
                    string workHours = spWorkMin.ToString(@"hh\:mm");
                    strCommand = "C8=" + workHours + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定是否线性温变控制：1-否 0-是
                    if (Global.Global.PtcBox.IsLineContrl == "Y")
                    {
                        strCommand = "CB=0" + "\r\n";
                    }
                    else
                    {
                        strCommand = "CB=1" + "\r\n";
                    }
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：2-低温浸润设定
                    strCommand = "C5=2" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置低温温度
                    strCommand = "C6=" + Global.Global.PtcBox.LowTemp + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置低温持续时间
                    spWorkMin = TimeSpan.FromMinutes((double)Global.Global.PtcBox.LowTime);
                    workHours = spWorkMin.ToString(@"hh\:mm");
                    strCommand = "C8=" + workHours + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置开始位置：1-高温 0-低温
                    if (Global.Global.PtcBox.StratPos == "High")
                    {
                        strCommand = "CB=1" + "\r\n";
                    }
                    else
                    {
                        strCommand = "CB=0" + "\r\n";
                    }
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：3-温变斜率和周期设定
                    strCommand = "C5=3" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定温变斜率
                    strCommand = "C6=" + Global.Global.PtcBox.XieLv + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定测试周期
                    strCommand = "C8=" + Global.Global.PtcBox.TestCycs + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定温度控制介质：0-空气 1-样式
                    if (Global.Global.PtcBox.TempContrl == "Air")
                    {
                        strCommand = "CB=0" + "\r\n";
                    }
                    else
                    {
                        strCommand = "CB=1" + "\r\n";
                    }
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：5-预处理设定
                    strCommand = "C5=5" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定预处理温度
                    strCommand = "C6=" + Global.Global.PtcBox.BeforTemp + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定预处理时间
                    spWorkMin = TimeSpan.FromMinutes((double)Global.Global.PtcBox.BeforTime);
                    workHours = spWorkMin.ToString(@"hh\:mm");
                    strCommand = "C8=" + workHours + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：6-尾处理设定
                    strCommand = "C5=6" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定尾处理温度
                    strCommand = "C6=" + Global.Global.PtcBox.AfterTemp + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定尾处理时间
                    spWorkMin = TimeSpan.FromMinutes((double)Global.Global.PtcBox.AfterTime);
                    workHours = spWorkMin.ToString(@"hh\:mm");
                    strCommand = "C8=" + workHours + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定步骤为：7-负载设定
                    strCommand = "C5=7" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定负载：0-标准 1-轻负载 2-重负载
                    if (Global.Global.PtcBox.Ysfz == "standard")
                    {
                        strCommand = "CB=0" + "\r\n";
                    }
                    else if (Global.Global.PtcBox.Ysfz == "light")
                    {
                        strCommand = "CB=1" + "\r\n";
                    }
                    else
                    {
                        strCommand = "CB=2" + "\r\n";
                    }
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设置高低温周期运行模式
                    strCommand = "C3=C" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //设定程序号为：1(随便设)
                    strCommand = "C4=1" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);
                    Thread.Sleep(50);

                    //开启温箱
                    strCommand = "C1=ON" + "\r\n";
                    Global.Global.BoxPort.Write(strCommand);
                    Debug.Write(strCommand);

                    Global.Global.PtcBox.IsOpen = true;
                    Global.Global.ValueBoxRunning = true;

                    Thread.Sleep(1000);
                    AutoRun.TimerCheckTemperature.Start();

                    Thread.Sleep(5000);


                    nowCycleNumber = (int)Global.Global.PtcBox.TestCycs;
                }

                for (int n = 0; n < channelListTemp.Count; n++)
                {
                    /*if (channelListTemp[n].State == "running")
                    {
                        continue;
                    }*/
                    channelListTemp[n].IRListStr.Clear();
                    channelListTemp[n].VRListStr.Clear();
                    channelListTemp[n].TJListStr.Clear();
                    channelListTemp[n].PWListStr.Clear();

                    channelListTemp[n].IROutPut = "";
                    channelListTemp[n].VROutPut = "";
                    channelListTemp[n].TJOutPut = "";
                    channelListTemp[n].PWOutPut = "";

                    channelListTemp[n].IROutPutCSV = "";
                    channelListTemp[n].VROutPutCSV = "";
                    channelListTemp[n].TJOutPutCSV = "";
                    channelListTemp[n].PWOutPutCSV = "";

                    channelListTemp[n].OutPutVoltCSV = "";
                    channelListTemp[n].IROutPutCSVIR = "";

                    //List<Position> tempList = new List<Position>();
                    for (int i = 0; i < Global.Global.ChannelPositionsCount; i++)
                    {
                        /*Position position = new Position(channelListTemp[n], i);

                        position.ID = channelListTemp[n].Positions[i].ID;
                        position.ChID = channelListTemp[n].Positions[i].ChID;
                        position.ChannelName = channelListTemp[n].Positions[i].ChannelName;
                        position.Index = channelListTemp[n].Positions[i].Index;
                        position.BasicValue = channelListTemp[n].Positions[i].BasicValue;
                        tempList.Add(position);*/

                        channelListTemp[n].IRListStr.Add("0");
                        channelListTemp[n].VRListStr.Add("0");
                        channelListTemp[n].TJListStr.Add("0");
                        channelListTemp[n].PWListStr.Add("0");
                    }
                    //channelListTemp[n].Positions = tempList;
                    channelListTemp[n].ExceptionInfo = "";
                    channelListTemp[n].IsRed = false;

                    //获取当前温箱周期数
                    channelListTemp[n].StartTempCycleNumber = nowCycleNumber;


                    //打开继电器
                    //foreach (var pos in channelListTemp[n].Positions)
                    //{
                    //    int powerIndex = channelListTemp[n].Index * channelListTemp[n].Positions.Count + pos.Index;
                    //    Global.Global.PLC_XINJE.SetDO((byte)powerIndex, pos.IsUse);
                    //    Thread.Sleep(50);
                    //}

                    //if (Global.Global.PtcBox.Status == "RUN" ) {
                    //    int syzqNumber = 0;
                    //    bool canNumber = int.TryParse(Global.Global.Syzq ,out syzqNumber);
                    //    if (canNumber) {
                    //        channelListTemp[n].StartTempCycleNumber = syzqNumber;
                    //    }
                    //}

                    Global.Global.Buttons[channelListTemp[n].Index].FillColor = Color.FromArgb(59, 59, 59);
                    Global.Global.Buttons[channelListTemp[n].Index].FillColor2 = Color.FromArgb(59, 59, 59);

                    //根据具体情况设置采样间隔
                    decimal CheckInterval = channelListTemp[n].TestParameter.CheckInterval;
                    if (CheckInterval == 0)
                    {
                        CheckInterval = 3;
                    }
                    if (channelListTemp[n].State == "stop")
                    {
                        channelListTemp[n].TimerForTestData.Interval = (double)(CheckInterval * 1000);
                        channelListTemp[n].RunningTime = new TimeSpan(0, 0, 0);

                        //测试时长开始计时
                        channelListTemp[n].StartTime = DateTime.Now;
                        channelListTemp[n].TimerForRunTimeLabel.Start();
                        Debug.WriteLine("state = stop-->running");
                    }
                    else if (channelListTemp[n].State == "pause")
                    {
                        channelListTemp[n].StartTime = DateTime.Now;
                        channelListTemp[n].TimerForRunTimeLabel.Start();
                        Debug.WriteLine("state = pause-->running");
                    }
                    //指示灯变绿
                    if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                    {
                        ThreeColor.EequeueCommandQueue("Green");
                    }
                    //改变老化板运行状态
                    channelListTemp[n].StateEnd = false;
                    channelListTemp[n].State = "running";

                    if (channelListTemp[n].IsCurrentChannel)
                    {
                        //重置文本框背景
                        for (int i = 0; i < Global.Global.LabelArrayIR.Count; i++)
                        {
                            Global.Global.LabelArrayIR[i].BackColor = Color.FromArgb(59, 59, 59);
                            Global.Global.CurrentChannel.Positions[i].IsFuse = false;
                            Global.Global.CurrentChannel.Positions[i].IsShort = false;
                            Global.Global.CurrentChannel.Positions[i].IsOver = false;
                            Global.Global.CurrentChannel.Positions[i].ExcBuffer.Clear();
                        }
                        for (int i = 0; i < Global.Global.LabelArrayVR.Count; i++)
                        {
                            Global.Global.LabelArrayVR[i].BackColor = Color.FromArgb(59, 59, 59);
                        }
                    }
                }

                //开启电源
                for (int m = 0; m < channelListTemp.Count; m++)
                {
                    Channel channel = channelListTemp[m];
                    if (!channel.PowerPack.IsWork)
                    {
                        Thread thread = new Thread(new ThreadStart(channel.PowerPack.StartWork));
                        thread.Start();
                        channel.PowerPack.WorkThread = thread;
                        Thread.Sleep(20);
                        foreach (var each in channel.PowerList)
                        {
                            if (!each.TimerForReadData.Enabled)
                            {
                                each.TimerForReadData.Start();
                            }
                        }
                    }
                }

                LoadingForm.LoadingHelper.CloseForm();
                UIMessageDialog.ShowMessageDialog(this, "测试已开始", UILocalize.InfoTitle, false, UIStyle.Colorful);
                return;
            }

        }

        private void BtnStopTest_Click(object sender, EventArgs e)
        {
            List<Channel> channelList = Global.Global.ChannelList;
            List<Channel> channelListTemp = new List<Channel>();
            List<Channel> channelListTemp2 = new List<Channel>();
            foreach (var checkBoxes in CheckBoxes)
            {
                if (checkBoxes.Checked)
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    channelListTemp.Add(channelList[tag]);
                }
                else
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    if (channelList[tag].State == "running")
                    {
                        channelListTemp2.Add(channelList[tag]);
                    }
                }

            }
            if ((channelListTemp.Count == 0))
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要暂停测试的老化板", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            //多选操作
            if (channelListTemp.Count > 0)
            {
                foreach (var channel in channelListTemp)
                {
                    if (channel.State != "running")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "并未处于测试状态，不需要停止测试。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                }

                if (!UIMessageDialog.ShowMessageDialog(this, "是否确定停止测试？", UILocalize.AskTitle, true, UIStyle.Colorful))
                {
                    return;
                }

                LoadingForm.LoadingHelper.ShowLoadingScreen();

                /*foreach (var channel in channelListTemp)
                {
                    channel.PauseTest();
                }*/

                //关闭电源
                foreach (var channel in channelListTemp)
                {
                    if (channel.PowerPack.IsWork)
                    {
                        channel.PowerPack.ChannelListPersonClose = channelListTemp;
                        Thread thread = new Thread(new ThreadStart(channel.PowerPack.StopWorkForPerson));
                        thread.Start();
                        Thread.Sleep(20);
                    }
                }

                //检查是否所有老化板程序都已结束
                /*int fg = 0;
                foreach (var channel in Global.Global.ChannelList)
                {
                    if (channel.State == "running")
                    {
                        fg = 1;
                        break;
                    }
                }
                if (fg != 1)
                {
                    if (Global.Global.PtcBox.IsOpen)
                    {
                        AutoRun.TimerCheckTemperature.Stop();
                        Thread.Sleep(1000);

                        //Global.Global.PtcBox.IsAtuoClose = false;
                        //关闭
                        string strCommand = "C1=OFF" + "\r\n";
                        Global.Global.BoxPort.Write(strCommand);

                        Thread.Sleep(1000);
                        AutoRun.TimerCheckTemperature.Start();

                        Global.Global.PtcBox.IsOpen = false;
                        Global.Global.ValueBoxRunning = false;
                    }
                    
                    Debug.WriteLine("没有老化板在测试，则将指示灯设置为黄色。");
                    //没有老化板在测试，则将指示灯设置为黄色。
                    if (Global.Global.PlcPort != null && Global.Global.PlcPort.IsOpen)
                    {
                        ThreeColor.EequeueCommandQueue("Yellow");
                    }
                }*/

                //Thread.Sleep(6000);
                LoadingForm.LoadingHelper.CloseForm();
                UIMessageDialog.ShowMessageDialog(this, "所选老化板测试已暂停", UILocalize.InfoTitle, false, UIStyle.Colorful);
                return;
            }
        }

        private void BtnResetTest_Click(object sender, EventArgs e)
        {
            List<Channel> channelList = Global.Global.ChannelList;
            List<Channel> channelListTemp = new List<Channel>();
            foreach (var checkBoxes in CheckBoxes)
            {
                if (checkBoxes.Checked)
                {
                    int tag = int.Parse(checkBoxes.Tag.ToString());
                    channelListTemp.Add(channelList[tag]);
                }

            }
            if ((channelListTemp.Count == 0))
            {
                UIMessageDialog.ShowMessageDialog(this, "请先选择要重置测试的老化板", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                return;
            }

            //多选操作
            if (channelListTemp.Count > 0)
            {
                foreach (var channel in channelListTemp)
                {
                    if (channel.State == "running")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "正处于测试状态，请先停止测试。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                    if (channel.State == "stop")
                    {
                        UIMessageDialog.ShowMessageDialog(this, channel.ChannelName + "处于空闲状态，不需要重置。", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        return;
                    }
                }

                if (!UIMessageDialog.ShowMessageDialog(this, "是否确定重置测试？", UILocalize.AskTitle, true, UIStyle.Colorful))
                {
                    return;
                }
                for (int n = 0; n < channelListTemp.Count; n++)
                {
                    channelListTemp[n].ResetTest();
                    if (channelListTemp[n].IsCurrentChannel)
                    {
                        Global.Global.CurrentChannel.ExceptionInfo = "";
                        Global.Global.CurrentChannel.IsRed = false;
                        //重置文本框背景
                        for (int i = 0; i < Global.Global.LabelArrayIR.Count; i++)
                        {
                            Global.Global.LabelArrayIR[i].BackColor = Color.FromArgb(59, 59, 59);
                            Global.Global.CurrentChannel.Positions[i].IsFuse = false;
                            Global.Global.CurrentChannel.Positions[i].IsShort = false;
                            Global.Global.CurrentChannel.Positions[i].IsOver = false;
                            Global.Global.CurrentChannel.Positions[i].ExcBuffer.Clear();
                        }
                        for (int i = 0; i < Global.Global.LabelArrayVR.Count; i++)
                        {
                            Global.Global.LabelArrayVR[i].BackColor = Color.FromArgb(59, 59, 59);
                        }
                        //重置老化板按钮颜色
                        int index = Global.Global.CurrentChannel.Index;
                        Global.Global.Buttons[index].FillColor = SystemColors.ActiveCaption;
                        Global.Global.Buttons[index].FillColor2 = SystemColors.ActiveCaption;

                    }
                    else
                    {
                        channelListTemp[n].ExceptionInfo = "";
                        channelListTemp[n].IsRed = false;
                        Global.Global.Buttons[channelListTemp[n].Index].FillColor = Color.FromArgb(59, 59, 59);
                        Global.Global.Buttons[channelListTemp[n].Index].FillColor2 = Color.FromArgb(59, 59, 59);
                    }
                }
                UIMessageDialog.ShowMessageDialog(this, "所选老化板测试已重置", UILocalize.InfoTitle, false, UIStyle.Colorful);
                return;
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            foreach (var channel in Global.Global.ChannelList)
            {
                if (channel.PowerPack.IsWork)
                {
                    UIMessageDialog.ShowMessageDialog(this, "有正式测试正在进行中，不能进行手动测试！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    break;
                }
            }
            if (Global.Global.SDTest != null)
            {
                return;
            }
            SDTest SDTest = new SDTest();
            SDTest.Show();
        }

        private void BtnSeleAll_Click(object sender, EventArgs e)
        {
            foreach (var checkbox in CheckBoxes)
            {
                checkbox.Checked = !checkbox.Checked;
            }
        }

        private void checkBox_CheckedChanged(object sender, EventArgs e)
        {
            if (Global.Global.CurrentChannel == null || Global.Global.CurrentChannel.State != "stop")
            {
                return;
            }
            CheckBox cb = (CheckBox)sender;
            int pIndex = int.Parse(cb.Tag.ToString());

            Global.Global.CurrentChannel.Positions[pIndex].IsUse = cb.Checked;
            int Index = Global.Global.CurrentChannel.Index * Global.Global.CurrentChannel.Positions.Count + pIndex;
            //Global.Global.PLC_XINJE.SetDO((byte)Index, Global.Global.CurrentChannel.Positions[pIndex].IsUse);
            Thread.Sleep(200);
        }

        private void TitleLable_Click(object sender, EventArgs e)
        {
            Process waveProcess1 = new Process();

            IntPtr OtherExeWnd;
            string ChartExePath;
            string ChartExeName = "实时曲线.exe";

            try
            {
                Channel currentChannel = Global.Global.CurrentChannel;
                if (currentChannel == null)
                {
                    UIMessageDialog.ShowMessageDialog(this, "请先在左侧选中一个通道", UILocalize.InfoTitle, false, UIStyle.Colorful);
                    return;
                }
                if (currentChannel.TestParameter == null)
                {
                    return;
                }

                string fileName;
                if (currentChannel.TestParameter.BatchNumber != "")
                {
                    fileName = "\\" + currentChannel.TestParameter.ProductModel + "-" + currentChannel.TestParameter.BatchNumber + "-C" + (currentChannel.Index + 1).ToString() + ".csv";
                }
                else
                {
                    fileName = "\\" + currentChannel.TestParameter.ProductModel + "-C" + (currentChannel.Index + 1).ToString() + ".csv";
                }
                string filePath = "D:\\测试数据";
                if (!Directory.Exists(filePath))
                {
                    return;
                }
                if (!File.Exists(filePath + fileName))
                {
                    return;
                }

                OtherExeWnd = Global.Global.ChartWHandle1;
                ChartExePath = "D:\\实时曲线\\实时曲线1#lot";
                waveProcess1.StartInfo.Arguments = "数据图形";

                FileInfo file = new FileInfo(ChartExePath + "\\" + historyFilePath);
                if (!file.Exists)
                {
                    File.Create(ChartExePath + "\\" + historyFilePath).Close();
                }

                if (file.Length > 0)
                {
                    MessageBox.Show(Global.Global.MainFrom, "实时曲线正在绘制中，请稍后再试", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                bool isOpenOne = false;
                //判断这个窗体是否有效
                if (OtherExeWnd != IntPtr.Zero)
                {
                    if (IsWindow(OtherExeWnd))
                    {
                        SetForegroundWindow(OtherExeWnd);
                        ShowWindow(OtherExeWnd, 3);//0表示隐藏窗口/1-正常显示（可从最小化恢复）/2-最小化/3-最大化//SW_SHOWNOACTIVATE = 4//SW_RESTORE = 9
                    }
                    else
                    {
                        isOpenOne = true;
                    }
                }
                else
                {
                    isOpenOne = true;
                }

                if (isOpenOne)
                {
                    waveProcess1.StartInfo.FileName = ChartExePath + "\\" + ChartExeName;
                    waveProcess1.StartInfo.WorkingDirectory = ChartExePath;
                    waveProcess1.StartInfo.CreateNoWindow = true;
                    waveProcess1.Start();
                }

                if (isOpenOne)
                {
                    Thread.Sleep(4000);//延时15s等待实时曲线软件初始化完毕
                    Global.Global.ChartWHandle1 = waveProcess1.MainWindowHandle;
                }

                //文件路径
                string needReadFilePath = filePath + fileName;
                //读取参数
                string needReadParam = ((Label)sender).Tag.ToString();

                File.WriteAllText(file.FullName, needReadFilePath + "^" + needReadParam);


                COPYDATASTRUCT cds;//定义消息结构体
                cds.dwData = (IntPtr)0;
                cds.cbData = System.Text.Encoding.UTF8.GetBytes("showHistoryRealTime").Length + 1;//字符串长度
                cds.lpData = "showHistoryRealTime";//字符串
                SendMessage(Global.Global.ChartWHandle1, 0x004a, 0, ref cds);

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
            }
        }

        private void TbProductModel_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (Global.Global.CurrentChannel == null || Global.Global.CurrentChannel.State != "stop" || Global.Global.CurrentChannel.TestParameter == null)
                {
                    return;
                }
                UITextBox TB = (UITextBox)sender;

                string ProductModel = TB.Text.Trim();
                //检查文件名是否合法
                if (string.IsNullOrWhiteSpace(ProductModel))
                {
                    UIMessageDialog.ShowMessageDialog(this, "产品型号不能为空，请输入！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    TB.Focus();
                    return;
                }
                if (ProductModel.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                {
                    //含有非法字符 \ / : * ? " < > | 等
                    UIMessageDialog.ShowMessageDialog(this, "产品型号含有非法字符，请重新输入！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                    TB.Focus();
                    return;
                }
                Global.Global.CurrentChannel.TestParameter.ProductModel = ProductModel;
            }
        }

        private void TbBatchNumber_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == 13)
            {
                if (Global.Global.CurrentChannel == null || Global.Global.CurrentChannel.State != "stop" || Global.Global.CurrentChannel.TestParameter == null)
                {
                    return;
                }
                UITextBox TB = (UITextBox)sender;

                string BatchNumber = TB.Text.Trim();
                //检查文件名是否合法
                if (string.IsNullOrWhiteSpace(BatchNumber))
                {
                    BatchNumber = "";
                }
                if (BatchNumber != "")
                {
                    if (BatchNumber.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
                    {
                        //含有非法字符 \ / : * ? " < > | 等
                        UIMessageDialog.ShowMessageDialog(this, "产品批号含有非法字符，请重新输入！", UILocalize.ErrorTitle, false, UIStyle.Colorful);
                        TB.Focus();
                        return;
                    }
                }
                Global.Global.CurrentChannel.TestParameter.BatchNumber = BatchNumber;
            }
        }
    }
}
